package fun.easycode.webterminal.common.config;

import fun.easycode.webterminal.common.contract.CheckException;
import fun.easycode.webterminal.common.contract.R;
import fun.easycode.webterminal.common.exception.SftpFileModifiedException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;


@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(CheckException.class)
    @ResponseBody
    ResponseEntity<?> handleCheckException(CheckException e) {
        return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                .body(R.error(e.getMessage()));
    }

    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseBody
    ResponseEntity<?> illegalArgumentException(IllegalArgumentException e) {
        return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                .body(R.error(e.getMessage()));
    }

    /**
     * 处理 SftpFileModifiedException 异常
     *
     * @param e SftpFileModifiedException
     * @return R
     */
    @ExceptionHandler(SftpFileModifiedException.class)
    @ResponseStatus(HttpStatus.CONFLICT) // 409 Conflict
    public R<Void> handleSftpFileModifiedException(SftpFileModifiedException e) {
        log.warn("SFTP 文件并发修改冲突: {}", e.getMessage());
        return R.error("文件在您编辑期间已被其他用户修改，请刷新后重试。");
    }

    /**
     * 处理通用异常
     *
     * @param e Exception
     * @return R
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) // 500 Internal Server Error
    public R<Void> handleGeneralException(Exception e) {
        log.error("系统内部错误: ", e);
        return R.error("系统内部错误，请联系管理员。");
    }

    /**
     * 默认异常处理, 超出范围的应该重点关注, 可以钉钉通知等多途径来解决问题
     * @param throwable
     * @return
     */
    @ExceptionHandler(Throwable.class)
    @ResponseBody
    ResponseEntity<?> defaultException(Throwable throwable){
        throwable.printStackTrace();
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(R.error(throwable.getMessage()));
    }
}